<template>
  <div
    style="
      background-color: white !important;
      height: 95%;
      box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2); /* 更强烈的凸出效果 */
    "
  >
    <el-divider content-position="left" class="custom-divider"
      >基本信息</el-divider
    >

    <!-- 头像上传开始，准确来说上传完成应该重新查找一下这个用户的个人信息 -->
    <div class="row">
      <div class="col1">用户头像</div>
      <el-avatar
        style="width: 100px; height: 100px"
        :src="user.head"
      ></el-avatar>
      <el-upload
        class="avatar-uploader"
        :action="loadUrl"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <i class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <!-- 头像上传结束 -->
    <div class="row">
      <div class="col1">用户昵称</div>
      <div class="col2">
        <el-input v-model="user.nickName"></el-input>
      </div>
    </div>
    <div class="row">
      <div class="col1">用户ID</div>
      <div class="col2">{{ user.id }}</div>
    </div>
    <div class="row">
      <div class="col1">用户邮箱</div>
      <div class="col2">
        <el-input placeholder="请输入邮箱" v-model="user.email"></el-input
        ><el-input placeholder="请输入验证码" v-model="verifyCode"></el-input>
        <el-button
          type="primary"
          :disabled="isButtonDisabled"
          @click="getCaptcha"
        >
          {{ countdownText }}
        </el-button>
      </div>
    </div>
    <div class="row">
      <div class="col1">用户性别</div>
      <div class="col2">
        <el-select v-model="user.sex" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
    </div>
    <el-button style="margin-left: 250px" @click="saveInfo">保存</el-button>
    <el-button style="margin-left: 50px" @click="openDialog"
      >修改密码</el-button
    >
    <!-- 因为密码加密方法是单向加密，不能解密，因此这里只需要验证验证码和邮箱和两次密码是否一致 -->
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input
        placeholder="请输入新密码"
        v-model="editPwdForm.password"
      ></el-input>
      <br /><br />
      <el-input
        placeholder="请确认新密码"
        v-model="editPwdForm.confirmPwd"
      ></el-input>
      <br /><br /><br />
      <div style="display: flex">
        <el-input placeholder="请输入验证码" v-model="verifyCode"></el-input>
        <el-button
          type="primary"
          :disabled="isButtonDisabled"
          @click="getCaptcha"
        >
          {{ countdownText }}
        </el-button>
      </div>
      <br><br>
      <el-button style="margin-left: 170px;" @click="editPassword">确认</el-button>
    </el-dialog>
    <!-- 修改密码结束 -->
  </div>
</template>  
      
<script>
import { sendEmail } from "../../api/emailSend";
import { getSelf, editSelf,editPwd } from "../../api/usrMG";
export default {
  name: "OwnInfo",
  data() {
    return {
      editPwdForm: {
        password: "",
        confirmPwd: "",
      },
      dialogVisible: false, //修改密码的dialog
      countdownSeconds: 6,
      countdownText: "获取验证码",
      isButtonDisabled: false,
      verifyCode: "", //验证码
      options: [
        { value: 1, label: "男" },
        { value: 2, label: "女" },
      ],
      loadUrl:
        "http://127.0.0.1:8088/loadImg/head?userId=" +
        localStorage.getItem("userId"),
      imageUrl: localStorage.getItem("head"), // 存储当前显示的图片 URL
      user: {
        //用户的个人数据
        id: "202403030001",
        email: "3173147072@qq.com",
        nickName: "热爱生活",
        password: "",
        userType: "1",
        sex: 2,
        head: "https://tyc-lianxi-oss1.oss-cn-chengdu.aliyuncs.com/headImage.jpg",
        delFlag: 0,
      },
    };
  },
  methods: {
    async editPassword() {
      //确认修改密码事件
      if (this.verifyInfo(this.user.email, this.user.nickName) == false) return;
      if (this.verifyCode == "" || this.verifyCode.length != 6) {
        //未正确输入验证码
        this.$message.error("请正确输入验证码");
        return;
      }
      if(this.editPwdForm.password.length <8 || this.editPwdForm.password.length>16){
        this.$message.error("密码长度需在8-16位之间")
        return;
      }
      if(this.editPwdForm.password != this.editPwdForm.confirmPwd){
        this.$message.error("两次输入的密码不一致")
        return;
      }
      await editPwd(this.user.id,this.verifyCode,this.user.email,this.editPwdForm.password).then(res=>{
        if(res.data.code == 200){
          this.$message.success(res.data.msg)
          this.getInfo()
          //成功修改就把这些变量设置为默认
          this.editPwdForm.password = ""
          this.editPwdForm.confirmPwd = ""
          this.verifyCode = ""
          this.dialogVisible = false
        }else{
          this.$message.error(res.data.code+"::"+res.data.msg)
        }
      })
    },
    handleClose() {
      //关闭修改密码提示框
      this.editPwdForm.password = "";
      this.editPwdForm.confirmPwd = "";
      this.verifyCode = "";
      this.dialogVisible = false;
    },
    openDialog() {
      //打开修改密码提示框
      this.dialogVisible = true;
    },
    async getInfo() {
      await getSelf(localStorage.getItem("userId")).then((res) => {
        if (res.data.code == 200) {
          this.user = res.data.data;
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
    },
    getCaptcha() {
      //发送验证码，点击验证码倒计时
      if (this.verifyInfo(this.user.email, this.user.nickName) == false) {
        //未输入邮箱
        return;
      }
      // 邮箱格式验证成功
      // 在这里可以调用你的后端 API 来获取验证码
      // 例如: sendEmail(this.user.email);
      sendEmail(this.user.email)
        .then((res) => {
          if (res.data.code == 200) this.$message.success(res.data.msg);
          else this.$message.error(res.data.msg);
        })
        .catch((err) => {
          console.log(err);
        });

      this.isButtonDisabled = true;
      this.countdownSeconds = 6; // 重置倒计时秒数
      this.countdownText = this.countdownSeconds + "s";

      const intervalId = setInterval(() => {
        if (this.countdownSeconds > 0) {
          this.countdownSeconds--;
          this.countdownText = this.countdownSeconds + "s";
        } else {
          clearInterval(intervalId);
          this.isButtonDisabled = false;
          this.countdownText = "获取验证码"; // 重置按钮文本
        }
      }, 1000);
    },
    verifyInfo(email, nickName) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (email == "" || email == null || emailRegex.test(email) == false) {
        this.$message.error("请输入正确邮箱");
        return false;
      }
      if (nickName.length < 4 || nickName.length > 16) {
        this.$message.error("请输入正确的昵称(4-16个字符)");
        return false;
      }
      return true;
    },
    async saveInfo() {
      //点击保存先验证一下输入格式是否正确
      if (this.verifyInfo(this.user.email, this.user.nickName) == false) {
        //未正确输入邮箱或者昵称
        return;
      }
      if (this.verifyCode == "" || this.verifyCode.length != 6) {
        //未正确输入验证码
        this.$message.error("请正确输入验证码");
        return;
      }
      // 保存数据
      await editSelf(this.verifyCode, this.user).then((res) => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.getInfo();
          localStorage.setItem("head", this.user.head);
          this.verifyCode = "";
          this.$emit("xiugaitouxiang");
        } else {
          this.$message.error(res.data.code + "::" + res.data.msg);
        }
      });
    },
    beforeAvatarUpload(file) {
      const isJPEG = file.type === "image/jpeg";
      const isJPG = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPEG && !isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    handleAvatarSuccess(res, file, fileList) {
      //上传图片组建的默认返回参数
      // 假设服务器返回的数据中包含图片的 URL
      if (res.code == 200) {
        this.user.head = res.data;
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.code + "::" + res.msg);
      }
      console.log(file, fileList);
    },
  },
  // 如果需要在组件加载时就显示某个默认的头像
  mounted() {
    // 这里可以调用 API 来获取默认头像的 URL，并赋值给 imageUrl
    // 例如：this.imageUrl = 'default-avatar-url';
    this.getInfo();
  },
};
</script>  
      
<style lang="scss" scoped>
.custom-divider {
  /* 找到并修改分割线上文本的 DOM 元素背景色 */
  .el-divider__text {
    box-shadow: 20px 10px 10px rgba(0, 0, 0, 0.2); /* 更强烈的凸出效果 */
    font-size: 25px;
    border-radius: 25px;
    text-align: center;
    line-height: 50px;
    width: 200px;
    height: 50px;
    font-weight: 700;
    background-color: #a6acaf; /* 替换成你想要的背景色 */
    color: #fff; /* 如果需要的话，也可以设置文本颜色 */
    padding: 0 5px; /* 根据需要添加内边距 */
    transition: background-color 500ms ease;
  }
  .el-divider__text:hover {
    background-color: #3d4a4a; /* 替换成自己设置背景色 */
  }
}
.avatar-uploader {
  border: 2px dashed #a09f9f;
  border-radius: 6px;
  cursor: pointer;
}
.avatar-uploader:hover {
  border-color: #06a4ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 80px;
  line-height: 80px;
  text-align: center;
}

.row {
  display: flex;
  // padding-top: 10px;
  padding-bottom: 10px;
  margin-bottom: 25px;
  border-bottom: 1px dashed #e2dada;
}
.col1 {
  display: flex;
  width: 100px;
  align-items: center;
  font-size: 14px;
  color: #6e7474;
  margin-right: 50px;
  margin-left: 150px;
  justify-content: space-between;
  text-align: justify;
  text-align-last: justify;
}

.col2 {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 17px;
  color: #6e7474;
}
</style>